#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：django32_celery 
@File    ：writeconfig.py
@IDE     ：PyCharm 
@Author  ：Toby
@Date    ：2024/5/2 11:38 
'''
from configparser import ConfigParser

"""
配置文件增删查改
"""
class CfgPar:
    def __init__(self, filename):
        self.config = ConfigParser()
        self.filename = filename
        self.encoding = 'UTF-8'
        self.config.read(self.filename, self.encoding)

    def get_section(self):

        for item in self.config.sections():
            print(item)
        return self.config.sections()
        # for i in self.config.sections():
        #     print(f"sections:{i}")

    def get_value(self, section, option):
        value = self.config.get(section, option)
        print(f'value:{value}')
        return value

    def get_items(self, section):
        """获取 items"""
        for key, value in self.config.items(section):
            print(f"option: {key}")
            print(f"value: {value}")

    def get_intitem(self,section,option):
        res = self.config.getint(section,option)
        return res

    def add_section(self, section):
        if not self.config.has_section(section):
            self.config.add_section(section)

        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)

    def add_items(self, section, option, value):

        if not self.config.has_section(section):
            self.config.add_section(section)
            print("add_section")
        # 前提：不存在 option 时
        if not self.config.has_option(section, option):
            # set：设置值（新增 或 修改）
            self.config.set(section, option, value)
            print('add_items')
        # 写入
        self.write_config(self.filename, self.encoding)

    def update_values(self, section, option, value):
        if not self.config.has_section(section):
            print('section is not exist')
        else:
            # 前提：存在 option 时
            if self.config.has_option(section, option):
                # 修改值
                self.config.set(section, option, value)
                # 写入
                self.write_config(self.filename, self.encoding)
            else:
                print("option is not exist!")



if __name__ == '__main__':
    cfg = CfgPar('./test.ini')
    cfg.add_section('abd')
    cfg.add_items('abc','host','123123')
    cfg.get_section()

    cfg.update_values('abc','host','232323233222332zzz')
